<template>
  <div class="data-container">
    <!-- 筛选部分 -->
    <div class="filter-section">
      <el-button-group>
        <el-button
          :type="activeType === 'realTime' ? 'primary' : ''"
          @click="handleTypeChange('realTime')">
          实时数据
        </el-button>
        <!-- <el-button
          :type="activeType === 'goods' ? 'primary' : ''"
          @click="handleTypeChange('goods')">
          带货数据
        </el-button> -->
      </el-button-group>

      <div class="right-controls">
        <el-select
          v-model="selectedTimeRange"
          @change="handleTimeRangeChange"
          style="width: 120px; margin-right: 10px">
          <el-option
            v-for="item in timeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
        <el-icon
          class="refresh"
          :size="20"
          @click="refreshData">
          <Refresh />
        </el-icon>
      </div>
    </div>

    <!-- 图表容器 -->
    <div
      ref="chartRef"
      class="chart-container"></div>
  </div>
</template>

<script setup lang="ts" name="FChart">
// FChart 组件用于显示直播数据图表
import { onMounted, onUnmounted, ref, shallowRef } from 'vue'
import * as echarts from 'echarts'
import {
    ElButton,
    ElButtonGroup,
    ElSelect,
    ElOption,
    ElIcon,
    ElMessage,
    dayjs
} from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { getOnlineDataApi } from '@/addon/htscrm/api'

type DataType = 'realTime' | 'goods'
type TimeRange = '2h' | '1d' | '3d'

const route = useRoute()
const chartRef = ref<HTMLElement>()
const chartInstance = shallowRef<echarts.ECharts>()
const activeType = ref<DataType>('realTime')
const selectedTimeRange = ref<TimeRange>('2h')

const timeOptions = [
    { value: '2h', label: '近2小时' },
    { value: '1d', label: '近1天' },
    { value: '3d', label: '近3天' }
]

// 模拟数据
const data = ref({
    time: [],
    online: [],
    guankan: [],
    dati: []
})

// 初始化图表
const initChart = async () => {
    if (!chartRef.value) return
    chartInstance.value = echarts.init(chartRef.value)
    fetchData()
}

const getOnlineData = async () => {
    const res = await getOnlineDataApi({
        id: route.params.id
    })
    res.data.sort((a, b) => dayjs(a.date).unix() - dayjs(b.date).unix())
    data.value.time = res.data.map(item => ({
        value: dayjs(item.date).format('HH:mm:ss')
    }))
    data.value.online = res.data.map(item => {
        return [dayjs(item.date).toDate(), item.online_num]
    })
    data.value.guankan = res.data.map(item => {
        return [dayjs(item.date).toDate(), item.guankan_num]
    })
    data.value.dati = res.data.map(item => {
        return [dayjs(item.date).toDate(), item.dati_num]
    })
}

// 更新图表配置
const updateChart = () => {
    const option: echarts.EChartsOption = {
        tooltip: {
            trigger: 'axis',
            valueFormatter: (value) => `${Number(value).toLocaleString()}`
        },
        legend: {
            top: 10,
            data: ['实时在线', '累计观看', '累计答题']
        },
        grid: {
            left: 50,
            right: 50,
            bottom: 50
        },
        xAxis: {
            type: 'time',
            boundaryGap: false
            // type: 'category',
            // data: data.value.time,
            // axisLine: { show: false },
            // axisLabel: {
            //     show: true
            //     // formatter: (value: string) => value
            // },
            // splitLine: {
            //     lineStyle: {
            //         type: 'dashed',
            //         color: '#e5e5e5'
            //     }
            // }
        },
        yAxis: {
            type: 'value',
            axisLine: { show: false },
            splitLine: {
                lineStyle: {
                    type: 'dashed',
                    color: '#e5e5e5'
                }
            },
            axisLabel: {
                formatter: (value: number) => `${value}`
            },
            minInterval: 1
        },
        series: [
            {
                name: '实时在线',
                type: 'line',
                data: data.value.online,
                smooth: true,
                lineStyle: { color: '#6589f0' },
                symbol: 'none'
            },
            {
                name: '累计观看',
                type: 'line',
                data: data.value.guankan,
                smooth: true,
                lineStyle: { color: '#7fc9ba' },
                symbol: 'none'
            },
            {
                name: '累计答题',
                type: 'line',
                data: data.value.dati,
                smooth: true,
                lineStyle: { color: '#9dc592' },
                symbol: 'none'
            }
        ]
    }

    console.log(option)

    chartInstance.value?.setOption(option)
}

// 切换数据类型
const handleTypeChange = (type: DataType) => {
    activeType.value = type
    fetchData()
}

// 切换时间范围
const handleTimeRangeChange = (val: TimeRange) => {
    selectedTimeRange.value = val
    fetchData()
}

// 刷新数据
const refreshData = () => {
    fetchData()
}

// 获取数据
const fetchData = async () => {
    // 这里调用API接口获取数据
    await getOnlineData()
    updateChart()
}

const timer = ref()

onMounted(() => {
    initChart()
    window.addEventListener('resize', () => chartInstance.value?.resize())

    clearInterval(timer.value)
    timer.value = setInterval(() => {
        refreshData()
    }, 10 * 1000)
})
onUnmounted(() => {
    clearInterval(timer.value)
})
</script>

<style lang="scss" scoped>
.data-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin-bottom: 20px;
}

.right-controls {
  display: flex;
  align-items: center;
}

.chart-container {
    flex: 1;
}

.refresh {
  cursor: pointer;
}
</style>
